package com.zz.yt.lib.annex.document.util;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.util.file.FilePathUtils;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.annex.R;
import com.zz.yt.lib.annex.document.DocumentView;
import com.zz.yt.lib.annex.document.bean.AnnexBean;

import java.util.ArrayList;
import java.util.List;

import droidninja.filepicker.FilePickerActivity;
import droidninja.filepicker.FilePickerBuilder;
import droidninja.filepicker.FilePickerConst;

/**
 * 选择文件的工具类
 *
 * @author qf
 * @version 2020-04-05
 */
public final class AnnexUtil {

    private Activity act;
    private Fragment fra;
    private ActivityResultLauncher<Intent> resultLauncher;
    private int reCode = FilePickerConst.REQUEST_CODE_DOC;
    private final FilePickerBuilder pickerBuilder = FilePickerBuilder.getInstance();

    private AnnexUtil() {
        act = Latte.getActivity();
        pickerBuilder.setActivityTitle("选择文件").setActivityTheme(R.style.LibAppTheme);
    }

    @NonNull
    public static AnnexUtil Bundle() {
        return new AnnexUtil()
                .setMaxCount(9)
                .enableDocSupport(true);
    }

    /**
     * @param activity：上下文对象
     */
    public AnnexUtil setContent(Activity activity) {
        this.act = activity;
        return this;
    }

    /**
     * @param fragment：上下文对象
     */
    public AnnexUtil setContent(Fragment fragment) {
        this.fra = fragment;
        return this;
    }

    /**
     * @param resultLauncher:api的直接回调方法，处理下文件的那个回调
     */
    public AnnexUtil setResultLauncher(ActivityResultLauncher<Intent> resultLauncher) {
        this.resultLauncher = resultLauncher;
        return this;
    }

    /**
     * @param maxCount：可选择文件数量
     */
    public AnnexUtil setMaxCount(int maxCount) {
        this.pickerBuilder.setMaxCount(maxCount);
        return this;
    }

    /**
     * 是否可以选择压缩文件
     */
    public AnnexUtil setZip() {
        final String[] zipTypes = {".zip", ".rar"};
        this.pickerBuilder.addFileSupport("ZIP", zipTypes, R.drawable.hf_file_rar);
        return this;
    }

    /**
     * @param status：启用文档支持
     */
    public AnnexUtil enableDocSupport(boolean status) {
        this.pickerBuilder.enableDocSupport(status);
        return this;
    }

    /**
     * @param requestCode：回调的requestCode
     */
    public AnnexUtil setRequestCode(int requestCode) {
        if (requestCode > 0) {
            this.reCode = requestCode;
        }
        return this;
    }

    /**
     * 发起获得文件
     */
    public void onAddAnnexClickListener() {
        PermissionUtils
                .permission(PermissionConstants.STORAGE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(@NonNull UtilsTransActivity activity, @NonNull ShouldRequest shouldRequest) {
                        shouldRequest.again(true);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(@NonNull List<String> permissionsGranted) {
                        LatteLogger.d("权限获取成功", permissionsGranted);
                        if (resultLauncher != null) {
                            LatteLogger.i("resultLauncher");
                            final Bundle bundle = new Bundle();
                            bundle.putInt(FilePickerConst.EXTRA_PICKER_TYPE, FilePickerConst.DOC_PICKER);
                            final Intent intent = new Intent();
                            if (fra == null) {
                                intent.setClass(act, FilePickerActivity.class);
                            } else {
                                intent.setClass(fra.getContext(), FilePickerActivity.class);
                            }
                            intent.putExtras(bundle);
                            resultLauncher.launch(intent);
                            return;
                        }
                        if (reCode != FilePickerConst.REQUEST_CODE_DOC) {
                            if (fra == null) {
                                pickerBuilder.pickFile(act, reCode);
                            } else {
                                pickerBuilder.pickFile(fra, reCode);
                            }
                            return;
                        }
                        if (fra == null) {
                            pickerBuilder.pickFile(act);
                        } else {
                            pickerBuilder.pickFile(fra);
                        }
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissionsDeniedForever, @NonNull List<String> permissionsDenied) {
                        LatteLogger.d("权限永久拒绝", permissionsDeniedForever);
                        LatteLogger.d("权限拒绝", permissionsDenied);
                    }
                })
                .theme(new PermissionUtils.ThemeCallback() {
                    @Override
                    public void onActivityCreate(@NonNull Activity activity) {
                        ScreenUtils.setFullScreen(activity);
                    }
                })
                .request();
    }


    /***
     * 设置附件数据，展示到界面(选择文件的activity 需要用onActivityResult接收)
     * @param view：展示附件控件
     * @param requestCode：
     * @param resultCode：
     * @param data：
     * @param listener：上传回调
     * @return 是否是附件回调
     */
    public boolean onResultAnnex(DocumentView view, int requestCode, int resultCode, Intent data, OnClickListener listener) {
        if (data != null && resultCode == Activity.RESULT_OK && requestCode == reCode) {
            final List<Uri> annexUri = data.getParcelableArrayListExtra(FilePickerConst.KEY_SELECTED_DOCS);
            if (annexUri != null && annexUri.size() > 0) {
                final List<String> annex = new ArrayList<>();
                for (Uri uri : annexUri) {
                    annex.add(FilePathUtils.getRealPathFromUri(Latte.getApplicationContext(), uri));
                }
                if (listener != null) {
                    listener.onClick(annex);
                }
                if (view != null) {
                    for (String ann : annex) {
                        view.addData(new AnnexBean(ann));
                    }
                }
            }
            return true;
        }
        return false;
    }

    /***
     * 设置附件数据，展示到界面(选择文件的activity 需要用onActivityResult接收)
     * @param requestCode：
     * @param resultCode：
     * @param data：
     * @param listener：上传回调
     * @return 是否是附件回调
     */
    public boolean onResultAnnex(int requestCode, int resultCode, Intent data, OnClickListener listener) {
        if (data != null && resultCode == Activity.RESULT_OK && requestCode == reCode) {
            final List<Uri> annexUri = data.getParcelableArrayListExtra(FilePickerConst.KEY_SELECTED_DOCS);
            final boolean is = annexUri != null && annexUri.size() > 0;
            if (listener != null) {
                final List<String> annex = new ArrayList<>();
                if (is) {
                    for (Uri uri : annexUri) {
                        annex.add(FilePathUtils.getRealPathFromUri(Latte.getApplicationContext(), uri));
                    }
                }
                listener.onClick(is ? annex : new ArrayList<String>());
            }
            return true;
        }
        return false;
    }

    /***
     * 设置附件数据，展示到界面(选择文件的activity 需要用onActivityResult接收)
     * @param result：
     * @return 是否是附件回调
     */
    @NonNull
    public static List<String> onResultList(ActivityResult result) {
        final List<String> annex = new ArrayList<>();
        if (result != null && result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
            final List<Uri> annexUri = result.getData().getParcelableArrayListExtra(FilePickerConst.KEY_SELECTED_DOCS);
            if (annexUri != null && annexUri.size() > 0) {
                for (Uri uri : annexUri) {
                    annex.add(FilePathUtils.getRealPathFromUri(Latte.getApplicationContext(), uri));
                }
            }
        }
        return annex;
    }

    /**
     * 选中的附件回调
     */
    public interface OnClickListener {
        /***
         * 选中的附件
         * @param path：选中的附件
         */
        void onClick(List<String> path);
    }

}
